package com.tianyuan.lims.common.render;

import com.jfinal.render.Render;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class InputStreamRender extends Render {
    private InputStream inputStream;
    private String fileName;
    private HttpServletResponse response;

    public InputStreamRender(InputStream inputStream, String fileName, HttpServletResponse response) {
        this.inputStream = inputStream;
        this.fileName = fileName;
        this.response = response;
    }

    @Override
    public void render() {
        HttpServletResponse response = this.response;
        try {
            // 处理中文文件名
            String encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
            // 设置正确的 MIME 类型（xlsx）
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 输出流到前端
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
